package com.neouton.crm.executiceManager.service.impl;

import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.neouton.common.entity.ActivitiVO;
import com.neouton.common.util.*;
import com.neouton.crm.approval.entity.ApprovalVO;
import com.neouton.crm.approval.service.IApprovalService;
import com.neouton.crm.dictionary.entity.DictionaryLookupItemVO;
import com.neouton.crm.dictionary.service.IDictionaryService;
import com.neouton.crm.entity.SysUserEntity;
import com.neouton.crm.executiceManager.entity.ManagerPurchaseOrderVO;
import com.neouton.crm.executiceManager.mapper.ManagerPurchaseOrderMapper;
import com.neouton.crm.executiceManager.service.IManagerPurchaseOrderService;
import com.neouton.crm.managerPayPlan.entity.ManagerPayPlan;
import com.neouton.crm.managerPayPlan.mapper.ManagerPayPlanMapper;
import com.neouton.crm.transpondEmail.service.TranspondEmailService;
import com.neouton.feginClient.FeginService;
import com.neouton.feginClient.WorkFlowFeginService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;
import java.util.concurrent.CompletableFuture;

@Service
public class ManagerPurchaseOrderServiceImpl implements IManagerPurchaseOrderService {


    @Resource
    private IDictionaryService dictionaryService;

    @Resource
    FeginService feginService;

    @Resource
    ManagerPurchaseOrderMapper managerPurchaseOrderMapper;

    @Resource
    private WorkFlowFeginService workFlowFeginService;

    @Resource
    private IApprovalService approvalService;

    @Resource
    private ManagerPayPlanMapper managerPaymentPlanMapper;

    @Resource
    private TranspondEmailService transpondEmailService;

    @Value("${webSit.web}")
    private String webSitUrl;
    /**
     * 分页查询综管采购列表
     *
     * @param page
     * @param entity
     * @return
     */
    public PageUtil<ManagerPurchaseOrderVO> queryPurchaseOrdesByPage(IPage page, ManagerPurchaseOrderVO entity, String token) {
        List<SysUserEntity> userList = this.queryUserList(AuthUtils.getUserId(), "managerPurchaseOrde", token);
        IPage<ManagerPurchaseOrderVO> iPage = managerPurchaseOrderMapper.queryPurchaseOrdesByPage(page, entity, userList);
        List<ManagerPurchaseOrderVO> list = iPage.getRecords();
        if (!list.isEmpty()) {
            BigDecimal totlePricePage = new BigDecimal(0);
            BigDecimal paymentMoneyPage = new BigDecimal(0);
            BigDecimal tickerMoneyPage = new BigDecimal(0);
            BigDecimal refundMoneyPage = new BigDecimal(0);
            for (ManagerPurchaseOrderVO pVo : list) {
                if (pVo.getTotlePrice() != null) {
                    totlePricePage = totlePricePage.add(new BigDecimal(pVo.getTotlePrice()));
                }
                if (pVo.getPaymentMoneys() != null) {
                    paymentMoneyPage = paymentMoneyPage.add(pVo.getPaymentMoneys());
                }
                if (pVo.getTickerMoneys() != null) {
                    tickerMoneyPage = tickerMoneyPage.add(pVo.getTickerMoneys());
                }
                if (pVo.getRefundMoney() != null) {
                    refundMoneyPage = refundMoneyPage.add(pVo.getRefundMoney());
                }
            }
            list.get(0).setTotlePricePage(String.valueOf(totlePricePage));
            list.get(0).setPaymentMoneyPage(String.valueOf(paymentMoneyPage));
            list.get(0).setTickerMoneyPage(String.valueOf(tickerMoneyPage));
            list.get(0).setRefundMoneyPage(String.valueOf(refundMoneyPage));
            iPage.setRecords(list);
        }
        return new PageUtil(iPage);
    }

    /**
     * 保存综管采购信息
     * @param purchaseOrder
     * @return
     */
    @Transactional
    public Integer saveOrUpdatePurchaseOrder(ManagerPurchaseOrderVO purchaseOrder,String token){
        //1.发起工作流
        //1）获取下一审批人，暂定总经理
        //获取审批人
        SysUserEntity user = dictionaryService.queryMenuUserIdsByCode("administrativeSpecialist").get(0);
        //获取人员信息
        Integer businessId = this.startPurchaseOrdeApproval(user);
        //2.记录本地审批数据
        //生成审批主表信息，日志信息
        ApprovalVO approval = approvalService.initApprovalAndLog(businessId, 41, purchaseOrder.getAskReason(),
                "", -1,"");
        //之后更新/保存
        purchaseOrder.setApprovalId(approval.getApprovalId());

        if( null == purchaseOrder.getPurchaseId() ){
            //生成采购单号
            purchaseOrder.setPurchaseNo(purchaseOrder.getPurchaseNo().replace("...",this.getPurchaseOrdeMaxNumByDate()));
            //保存主表信息
            managerPurchaseOrderMapper.savePurchaseOrder(purchaseOrder);
            ManagerPurchaseOrderVO purchaseOrderVO = this.getPurchaseOrdeInfoById(purchaseOrder.getPurchaseId());
            //保存付款计划
            List<ManagerPayPlan> paymentPlanList = new ArrayList<>();
            for (ManagerPayPlan paymentPlan : purchaseOrder.getPaymentPlans()) {
                paymentPlan.setPurchaseTopic(purchaseOrder.getPurchaseTopic());
                paymentPlan.setPurchaseId(purchaseOrder.getPurchaseId());
                paymentPlan.setApprovalId(approval.getApprovalId());
                paymentPlan.setPurchaseNo(purchaseOrderVO.getPurchaseNo());
                paymentPlan.getSupplier().setSupplierId(purchaseOrder.getSupplier().getSupplierId());
                paymentPlanList.add(paymentPlan);
            }
            managerPaymentPlanMapper.saveManagerPayPlan(paymentPlanList);
        }else {
            //1.备份主表信息
            //2.备份从表信息
            managerPurchaseOrderMapper.backUpPurchaseOrder(purchaseOrder);
            managerPaymentPlanMapper.backUpManagerPayPlan(purchaseOrder.getPurchaseId(),AuthUtils.getUserId());
            managerPurchaseOrderMapper.updatePurchaseOrder(purchaseOrder);
            List<ManagerPayPlan> paymentPlanList = new ArrayList<>();
            for (ManagerPayPlan paymentPlan : purchaseOrder.getPaymentPlans()) {
                paymentPlan.setPurchaseId(purchaseOrder.getPurchaseId());
                paymentPlan.setPurchaseNo(purchaseOrder.getPurchaseNo());
                paymentPlan.setPlanPeriod(String.valueOf(Integer.parseInt(paymentPlan.getPlanPeriod()) -1));
                paymentPlan.setApprovalId(purchaseOrder.getApprovalId());
                paymentPlan.setPlanPeriod(String.valueOf(Integer.parseInt(paymentPlan.getPlanPeriod())+1));
                paymentPlanList.add(paymentPlan);
            }
            managerPaymentPlanMapper.updateManagerPayPlanByIds(purchaseOrder.getPaymentPlans(),purchaseOrder.getPurchaseId());
        }
        //保存从表信息
        managerPurchaseOrderMapper.savePurchaseOrderProduct(purchaseOrder.getPurchaseOrderProducts(),purchaseOrder.getPurchaseId());
        //保存抄送人
        transpondEmailService.insertTranspondEmailInfoByUser(purchaseOrder.getApprovalId(),purchaseOrder.getForwardUsers());

        if(AuthUtils.getUserAccount().equals(user.getAccount())){
            //跳过第一步审批
            this.approvePurchaseOrderInfo(purchaseOrder,token,true);
        }else {
            //发送审批邮件
            //发送邮件
            approvalService.updateNextApproverByApprovalId(user.getUserId(),approval.getApprovalId());
//            String titel = "【系统通知】综管采购信息 - 流程单审批通知";
//            String msg = "<div><p >" + "尊敬的" + user.getLoginName() + "：</p></div>" +
//                    "<div><p style='text-indent: 2em'>您好，您有一张新的综管综管采购信息审批需要处理：</p></div>"+
//                    "<div><p style='text-indent: 2em'>事项编号："+approval.getApprovalCode()+"</p></div>"+
//                    "<div><p style='text-indent: 2em'>申请人："+ AuthUtils.getUserName() +" / "+ AuthUtils.getUserAccount()+"</p></div>"+
//                    "<div><p style='text-indent: 2em'>申请原因："+ (StringUtils.isEmpty(purchaseOrder.getAskReason()) ? "无":purchaseOrder.getAskReason())+"</p></div>"+
//                    "<div><p style='text-indent: 2em'>申请时间："+ DateUtils.getCurrentTime() +"</p></div>"+
//                    "<div><p style='text-indent: 2em'>采购名称："+purchaseOrder.getPurchaseTopic()+"</p></div>"+
//                    "<div><p style='text-indent: 2em'>采购单号："+purchaseOrder.getPurchaseNo()+"</p></div>"+
//                    "<div><p style='text-indent: 2em'>付款期次：共"+purchaseOrder.getPaymentPlanPeriod()+"期</p></div>"+
//                    "<div><p style='text-indent: 2em'>系统审批路径：客户关系管理系统 - 待办事项 - 待办审批 " +
//                    "<a href='"+webSitUrl+"/?m=crm&p=crmtodoItems&me=todoApprovalPath'>进入</a></p></div>"+
//                    "<div><p style='text-indent: 2em'>谢谢！</p></div>"+
//                    "<div><p style='text-indent: 2em'>说明：该邮件为系统自动发送，请勿回复。</p></div>";
//            CompletableFuture.runAsync(() -> EmailUtils.sentMailByAddressee(user.getEmail(),null,titel,msg,token));
            //调用通知接口生成待办通知
            Integer userId = AuthUtils.getUserId();
            CompletableFuture.runAsync(() -> NoticUtils.pushNotic(approval.getApprovalId(), new Timestamp(System.currentTimeMillis()),
                    userId,0,41,user.getUserId(),token));
        }
        return purchaseOrder.getPurchaseId();
    }


    /**
     * 更具采购单ID获取综管采购信息
     * @param purchaseOrdeId
     * @return
     */
    public ManagerPurchaseOrderVO getPurchaseOrdeInfoById(Integer purchaseOrdeId){
        ManagerPurchaseOrderVO purchaseOrder = managerPurchaseOrderMapper.getPurchaseOrdeInfoById(purchaseOrdeId);
        purchaseOrder.setForwardUsers(
                transpondEmailService.queryTranspondByApprovalId(purchaseOrder.getApproval().getApprovalId()));
        return purchaseOrder;
    }

    /**
     * 综管采购信息驳回审批
     * @param purchaseOrder
     * @return
     */
    @Transactional
    public Boolean rejectionPurchaseOrderInfo(ManagerPurchaseOrderVO purchaseOrder, String token){
        //获取工作流ID
        ApprovalVO approval = approvalService.queryApprovalByAppID(purchaseOrder.getApprovalId());
        ActivitiVO activitiVO = new ActivitiVO();
        activitiVO.setBusinessId(approval.getBusinessId());
        activitiVO.setAuthorization(AuthUtils.getUserAccount());
        //删除流程实例
        workFlowFeginService.deleteInstance(activitiVO);
        //驳回
        SysUserEntity user = null;
        Integer workState;
        String titel;
        String msg;
        Integer todoUser;
        SysUserEntity askUser = feginService.searchUserInfoById(approval.getCreator(),token).getResult();
        //当第一步为商务时，驳回至起点
        user = askUser;
        workState = 1;
        titel= "【系统通知】综管采购信息 - 流程单审批驳回通知";
        msg = "<div><p >" + "尊敬的" + askUser.getLoginName() + "：</p></div>" +
                "<div><p style='text-indent: 2em'>您好，您提交的综管采购信息审批已被驳回：</p></div>"+
                "<div><p style='text-indent: 2em'>事项编号："+approval.getApprovalCode()+"</p></div>"+
                "<div><p style='text-indent: 2em'>审批人："+askUser.getLoginName()+" / "+askUser.getAccount()+"</p></div>"+
                "<div><p style='text-indent: 2em'>审批意见："+(StringUtils.isEmpty(purchaseOrder.getAppReason()) ? "无":purchaseOrder.getAppReason())+"</p></div>"+
                "<div><p style='text-indent: 2em'>审批时间："+ DateUtils.getCurrentTime() +"</p></div>"+
                "<div><p style='text-indent: 2em'>采购名称："+purchaseOrder.getPurchaseTopic()+"</p></div>"+
                "<div><p style='text-indent: 2em'>采购单号："+purchaseOrder.getPurchaseNo()+"</p></div>"+
                "<div><p style='text-indent: 2em'>付款期次：共"+purchaseOrder.getPaymentPlanPeriod()+"期</p></div>"+
                "<div><p style='text-indent: 2em'>系统查看路径：客户关系管理系统 - 项目信息管理 - 项目信息 " +
                "<a href='"+webSitUrl+"/?m=crm&p=projectmanage&me=projectmanageInfo'>进入</a></p></div>"+
                "<div><p style='text-indent: 2em'>谢谢！</p></div>"+
                "<div><p style='text-indent: 2em'>说明：该邮件为系统自动发送，请勿回复。</p></div>";
        approvalService.approvalRejection(null,purchaseOrder.getApprovalId());
        todoUser = 0;
        //记录日志
        approvalService.insertApprovalLog(approval.getApprovalId(),"驳回",
                "",purchaseOrder.getAppReason());
        SysUserEntity finalUser = user;
        CompletableFuture.runAsync(() -> EmailUtils.sentMailByAddressee(finalUser.getEmail(),null,titel,msg,token));
        Integer userId = AuthUtils.getUserId();
        CompletableFuture.runAsync(() -> NoticUtils.pushNotic(purchaseOrder.getApprovalId(),  approval.getCreateDataTime(),
                userId,workState,41,todoUser,token));
        return true;
    }

    /**
     * 综管采购信息通过审批
     * @param purchaseOrder
     * @return
     */
    @Transactional
    public Boolean approvePurchaseOrderInfo(ManagerPurchaseOrderVO purchaseOrder,String token,Boolean auto){
        //获取工作流ID
        ApprovalVO approval = approvalService.queryApprovalByAppID(purchaseOrder.getApprovalId());
        ActivitiVO activitiVO = new ActivitiVO();
        activitiVO.setBusinessId(approval.getBusinessId());
        activitiVO.setAuthorization(AuthUtils.getUserAccount());
        ResponseAPI<ActivitiVO> processNodeNameAndCode = workFlowFeginService.getProcessNodeNameAndCode(activitiVO);
        SysUserEntity user = null;
        Integer workState;
        String titel;
        String msg;
        Integer todoUser;
        String ccUser = null;
        //整体通过
        SysUserEntity askUser = feginService.searchUserInfoById(approval.getCreator(),token).getResult();
        //记录审批日志
        if(auto){
            approvalService.insertApprovalLog(approval.getApprovalId(),"通过",
                    "系统判定跳过",purchaseOrder.getAppReason());
        }else {
            //记录日志
            approvalService.insertApprovalLog(approval.getApprovalId(),"通过",
                    "",purchaseOrder.getAppReason());
        }
        if( "董事长审批".equals(processNodeNameAndCode.getResult().getName()) ){
            //审批通过
            workFlowFeginService.approvalProcessByBusinessId(activitiVO);
            user=askUser;
            workState = 1;
            todoUser = 0;
            titel= "【系统通知】综管采购信息 - 流程单审批通过通知";
            msg =  "<div><p >" + "尊敬的" + user.getLoginName() + "：</p></div>" +
                    "<div><p style='text-indent: 2em'>您好，您提交的综管采购信息审批已通过：</p></div>"+
                    "<div><p style='text-indent: 2em'>事项编号："+approval.getApprovalCode()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>采购名称："+purchaseOrder.getPurchaseTopic()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>采购单号："+purchaseOrder.getPurchaseNo()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>付款期次：共"+purchaseOrder.getPaymentPlanPeriod()+"期</p></div>"+
                    "<div><p style='text-indent: 2em'>系统查看路径：客户关系管理系统 - 项目信息管理 - 项目信息 " +
                    "<a href='"+webSitUrl+"/?m=crm&p=projectmanage&me=projectmanageInfo'>进入</a></p></div>"+
                    "<div><p style='text-indent: 2em'>谢谢！</p></div>"+
                    "<div><p style='text-indent: 2em'>说明：该邮件为系统自动发送，请勿回复。</p></div>";
            ccUser = queryManagerPurchaseOrderCC();
            approvalService.approved(null,purchaseOrder.getApprovalId());
            String transpondEmails = transpondEmailService.selectTranspondEmailStr(purchaseOrder.getApprovalId());
            if(!transpondEmails.isEmpty()){
                ccUser = ccUser + "," + transpondEmails;
            }
            String finalCcUser = ccUser;
            SysUserEntity finalUser = user;
            CompletableFuture.runAsync(() -> EmailUtils.sentMailByAddressee(finalUser.getEmail(), finalCcUser,titel,msg,token));
            CompletableFuture.runAsync(() -> NoticUtils.pushNotic(purchaseOrder.getApprovalId(),  approval.getCreateDataTime(),
                    approval.getCreator(),workState,41,todoUser,token));
        }else {
            if("行政专员审批".equals(processNodeNameAndCode.getResult().getName())){
                user = dictionaryService.queryMenuUserIdsByCode("personnelManager").get(0);
                activitiVO.getCustomParams().put("personnelManager",user.getAccount());
            }else if("人事经理审批".equals(processNodeNameAndCode.getResult().getName())){
                user = dictionaryService.queryMenuUserIdsByCode("finance").get(0);
                activitiVO.getCustomParams().put("finance",user.getAccount());
            }else if("财务审批".equals(processNodeNameAndCode.getResult().getName())){
                user = dictionaryService.queryMenuUserIdsByCode("chairman").get(0);
                activitiVO.getCustomParams().put("chairman",user.getAccount());
            }
            //审批通过（使用动态入参传入下一审批人）
            workFlowFeginService.approvalProcessCustomUserByBusinessId(activitiVO);
            //获取下一节点
            ResponseAPI<ActivitiVO> nextProcessNodeNameAndCode = workFlowFeginService.getProcessNodeNameAndCode(activitiVO);
            if(nextProcessNodeNameAndCode.getResult().getAssignee().equals(processNodeNameAndCode.getResult().getAssignee())){
                this.approvePurchaseOrderInfo(purchaseOrder,token,true);
            }else {
                workState = 0;
                //交由下一审批人处理
                todoUser = user.getUserId();
//                titel= "【系统通知】综管采购信息 - 流程单审批通知";
//                msg = "<div><p >" + "尊敬的" + user.getLoginName() + "：</p></div>" +
//                        "<div><p style='text-indent: 2em'>您好，您有一张新的综管采购信息审批需要处理：</p></div>"+
//                        "<div><p style='text-indent: 2em'>事项编号："+approval.getApprovalCode()+"</p></div>"+
//                        "<div><p style='text-indent: 2em'>申请人："+askUser.getLoginName()+ " / " + askUser.getAccount() +"</p></div>"+
//                        "<div><p style='text-indent: 2em'>申请原因："+ (StringUtils.isEmpty(purchaseOrder.getAskReason()) ? "无":purchaseOrder.getAskReason())+"</p></div>"+
//                        "<div><p style='text-indent: 2em'>申请时间："+ DateUtils.getCurrentTime() +"</p></div>"+
//                        "<div><p style='text-indent: 2em'>采购名称："+purchaseOrder.getPurchaseTopic()+"</p></div>"+
//                        "<div><p style='text-indent: 2em'>采购单号："+purchaseOrder.getPurchaseNo()+"</p></div>"+
//                        "<div><p style='text-indent: 2em'>付款期次：共"+purchaseOrder.getPaymentPlanPeriod()+"期</p></div>"+
//                        "<div><p style='text-indent: 2em'>系统审批路径：客户关系管理系统 - 待办事项 - 待办审批 " +
//                        "<a href='"+webSitUrl+"/?m=crm&p=crmtodoItems&me=todoApprovalPath>进入</a></p></div>"+
//                        "<div><p style='text-indent: 2em'>谢谢！</p></div>"+
//                        "<div><p style='text-indent: 2em'>说明：该邮件为系统自动发送，请勿回复。</p></div>";
//                String finalCcUser = ccUser;
//                SysUserEntity finalUser = user;
//                CompletableFuture.runAsync(() -> EmailUtils.sentMailByAddressee(finalUser.getEmail(), finalCcUser,titel,msg,token));
                approvalService.updateNextApproverByApprovalId(user.getUserId(),purchaseOrder.getApprovalId());
                CompletableFuture.runAsync(() -> NoticUtils.pushNotic(purchaseOrder.getApprovalId(),  approval.getCreateDataTime(),
                        approval.getCreator(),workState,41,todoUser,token));
            }
        }
        return true;
    }

    /**
     * 通过申请表主键查询现有数据
     * @param approvalId
     * @return
     */
    public ManagerPurchaseOrderVO queryPurchaseOrderByApprovalId(Integer approvalId){
        ManagerPurchaseOrderVO purchaseOrder = managerPurchaseOrderMapper.queryPurchaseOrderByApprovalId(approvalId);
        purchaseOrder.setForwardUsers(transpondEmailService.queryTranspondByApprovalId(approvalId));
        return purchaseOrder;
    }

    /**
     * 通过申请表主键查询历史
     * @param approvalId
     * @return
     */
    public ManagerPurchaseOrderVO queryPurchaseOrderHistoryByApprovalId(Integer approvalId){
        ManagerPurchaseOrderVO purchaseOrder = managerPurchaseOrderMapper.queryPurchaseOrderHistoryByApprovalId(approvalId);
        if(purchaseOrder == null){
            purchaseOrder = managerPurchaseOrderMapper.queryPurchaseOrderByApprovalId(approvalId);
        }
        purchaseOrder.setForwardUsers(transpondEmailService.queryTranspondByApprovalId(approvalId));
        return purchaseOrder;
    }

    @Override
    public List<ManagerPayPlan> queryManagerPayPlanByPidAndPlanPeriod(ManagerPayPlan paymentPlan) {
        List<String> planPeriods = new ArrayList<>();
        if(!com.mysql.cj.util.StringUtils.isNullOrEmpty(paymentPlan.getPlanPeriod())){
            if(paymentPlan.getPlanPeriod().indexOf(",") >0) {
                for (String planPeriod:paymentPlan.getPlanPeriod().split(",")) {
                    planPeriods.add(planPeriod);
                }
                paymentPlan.setPlanPeriods(planPeriods);
                paymentPlan.setPlanPeriod(null);
            }
        }
        return managerPaymentPlanMapper.queryManagerPayPlanByPidAndPlanPeriod(paymentPlan);
    }

    @Override
    public List<ManagerPurchaseOrderVO> queryALLPurchaseOrders(String token) {
        return managerPurchaseOrderMapper.queryALLPurchaseOrders();
    }


    /**
     * 人员过滤器
     * @param userId
     * @param authCode
     * @param token
     * @return
     */
    public List<SysUserEntity> queryUserList(Integer userId,String authCode, String token) {
        List<SysUserEntity> userList = new ArrayList<>();
        List<SysUserEntity> authUserIList = dictionaryService.queryAuthUserIdsByCode(authCode);
        boolean result = false;
        for (SysUserEntity user:authUserIList) {
            if (Objects.equals(user.getUserId(), userId)) {
                result = true;
            }
        }
        if (result) {
            userList = feginService.getUserIgnoreFlag(token).getResult();
        } else {
            SysUserEntity user = feginService.searchUserInfoByIds(userId,token).getResult();
            if (user.getIsLeader() == 1) {
                userList = feginService.recursiveQueryAllUserByLeaderId(userId, token).getResult();
            }
            userList.add(user);
        }
        return userList;
    }

    /**
     * 获取当日最大采购单号
     * @return
     */
    public String getPurchaseOrdeMaxNumByDate(){
        Integer num = managerPurchaseOrderMapper.getPurchaseOrdeMaxNumByDate();
        if(num<10)
            return "0"+num;
        else
            return num.toString();
    }



    public Boolean deletePurchaseOrderById(Integer purchaseOrdeId){
        return managerPurchaseOrderMapper.deletePurchaseOrderById(purchaseOrdeId);
    }

    /**
     * 综管采购列表导出
     *
     * @param response
     */
    public void exportPurchaseOrdes(HttpServletResponse response, ManagerPurchaseOrderVO entit, String token) throws Exception{
        List<SysUserEntity> userList = this.queryUserList(AuthUtils.getUserId(),"managerPurchaseOrde", token);
        List<ManagerPurchaseOrderVO> purchaseOrdes = managerPurchaseOrderMapper.queryPurchaseOrdes(entit,userList);
        List<String> codes = new ArrayList<>();
        codes.add("paymentPlanPeriod");
        codes.add("managerPurchaseType");
        Map<String, List<DictionaryLookupItemVO>> stringListMap = dictionaryService.queryDictionaryLookupInfo(null, codes);
        for (int i = 0; i < purchaseOrdes.size(); i++) {
            ManagerPurchaseOrderVO purchaseOrder = purchaseOrdes.get(i);
            //付款期次
            for(DictionaryLookupItemVO dictionaryLookupItemVO : stringListMap.get("paymentPlanPeriod") ){
                if(dictionaryLookupItemVO.getItemCode().equals(purchaseOrder.getPaymentPlanPeriod()+"")){
                    purchaseOrder.setPaymentPlanPeriodStr(dictionaryLookupItemVO.getItemName());
                    break;
                }
            }
            //采购类型
            for(DictionaryLookupItemVO dictionaryLookupItemVO : stringListMap.get("managerPurchaseType") ){
                if(dictionaryLookupItemVO.getItemCode().equals(purchaseOrder.getPurchaseType()+"")){
                    purchaseOrder.setPurchaseTypeStr(dictionaryLookupItemVO.getItemName());
                    break;
                }
            }

            if(0 == purchaseOrder.getApproval().getApprovalStatus()){
                purchaseOrder.setApprovalStr("审批中");
            }else if(1 == purchaseOrder.getApproval().getApprovalStatus()){
                purchaseOrder.setApprovalStr("已通过");
            }else if(2 == purchaseOrder.getApproval().getApprovalStatus()){
                purchaseOrder.setApprovalStr("已驳回");
            }else if(3 == purchaseOrder.getApproval().getApprovalStatus()){
                purchaseOrder.setApprovalStr("已撤回");
            }else if(5 == purchaseOrder.getApproval().getApprovalStatus()){
                purchaseOrder.setApprovalStr("撤回中");
            }
            purchaseOrder.setPurchaseDateStr(String.format("%tY-%<tm-%<td",purchaseOrder.getPurchaseDate()));
        }

        //获取yml模板位置
        YamlPropertiesFactoryBean factoryBean = new YamlPropertiesFactoryBean();
        String path = "application.yml";
        factoryBean.setResources(new ClassPathResource(path));
        Properties properties = factoryBean.getObject();
        String contractTemplatePath = String.valueOf(properties.get("report.managerPurchaseTemplate"));

        //依据根目录获取模板位置
        TemplateExportParams params = new TemplateExportParams(contractTemplatePath);
        Map<String, Object> map = new HashMap<>();
        map.put("purchaseInfos",purchaseOrdes);
        ReportUtils.exportExcel(params,map,"采购列表",response);
    }

    /**
     * 开启审批流程
     * @param
     * @param user
     * @return
     */
    private Integer startPurchaseOrdeApproval(SysUserEntity user){
        ActivitiVO activitiVO = new ActivitiVO();
        activitiVO.setAuthorization(AuthUtils.getUserAccount());
        activitiVO.setProcessName("综管采购审批");
        activitiVO.setProcessCode("manager_purchaseOrde_approval");
        activitiVO.setNextNodeParams("administrativeSpecialist");
        //商务负责人
        SysUserEntity business = dictionaryService.queryMenuUserIdsByCode("administrativeSpecialist").get(0);
        activitiVO.setNextNodeAssignee(business.getAccount());
        ResponseAPI<ActivitiVO> responseAPI = workFlowFeginService.startMaxVersionProcessByDesignCodeCustomParams(activitiVO);
        return responseAPI.getResult().getBusinessId();
    }

    /**
     * 获取采购抄送人
     * @return
     */
    private String queryManagerPurchaseOrderCC(){
        //获取抄送人
        List<SysUserEntity> userIds = dictionaryService.queryCcUserIdsByCode("managerPurchaseOrderCC");
        StringBuilder emailList = new StringBuilder();
        for (int i = 0; i < userIds.size(); i++) {
            if (userIds.size()-1 == i){
                emailList.append(userIds.get(i).getEmail());
            }else {
                emailList.append(userIds.get(i).getEmail());
                emailList.append(",");
            }
        }
        return emailList.toString();
    }

    /**
     * 分页查询待办信息
     *
     * @param page
     * @param entity
     * @return
     */
    public PageUtil<ManagerPurchaseOrderVO> queryApprovalPurByPage(IPage page, ManagerPurchaseOrderVO entity){
        //获取工作流待办
        ActivitiVO activitiVO = new ActivitiVO();
        activitiVO.setAuthorization(AuthUtils.getUserAccount());
        ResponseAPI<List<ActivitiVO>> workFlowVoResponseAPI = workFlowFeginService.getTasksByAuthorization(activitiVO);
        List<ActivitiVO> activitiVOS = workFlowVoResponseAPI.getResult();
        if( activitiVOS == null || activitiVOS.size() == 0 ){
            return new PageUtil(new PageDTO());
        }else{
            return new   PageUtil(  managerPurchaseOrderMapper.queryApprovalPurByPage(page, entity,activitiVOS));
        }
    }

    /**
     * 分页查询已办信息
     *
     * @param page
     * @param entity
     * @return
     */
    public PageUtil<ManagerPurchaseOrderVO> queryApprovalPurDoneByPage(IPage page, ManagerPurchaseOrderVO entity){
        IPage<ManagerPurchaseOrderVO> iPage = managerPurchaseOrderMapper.queryApprovalPurDoneByPage(page, entity);
        return new PageUtil(iPage);
    }


    /**
     * 分页查询申请记录信息
     *
     * @param page
     * @param entity
     * @return
     */
    public PageUtil<ManagerPurchaseOrderVO> queryApprovalPurRecordByPage(IPage page, ManagerPurchaseOrderVO entity,String token){
        List<SysUserEntity> userList = this.queryUserList(AuthUtils.getUserId(),"approvalRecord", token);
        IPage<ManagerPurchaseOrderVO> iPage = managerPurchaseOrderMapper.queryApprovalPurRecordByPage(page, entity,userList);
        return new PageUtil(iPage);
    }
}
